﻿using System;
using RazakiBLL.Managers;
using RazakiBLL.Entities;

namespace RazakiBLL
{
    public static class ExceptionManager
    {
        private static readonly string _logLock = string.Empty;

        /// <summary>
        /// return value: 1=success, 0=fail
        /// </summary>
        /// <returns></returns>
        public static int Log(Exception exc, int? parentId = null)
        {
            lock (_logLock)
            {
                int result = UtilitiesBLL._DECLINE_ID;
                int newRecordId = UtilitiesBLL._DECLINE_ID;
                ExceptionLog exceptionLog;
                UowRazaki uowRazaki = new UowRazaki();

                //logging
                exceptionLog = new ExceptionLog
                                   {
                                       Type = exc.GetType().FullName,
                                       Message = exc.Message,
                                       StackTrace = exc.StackTrace,
                                       LastUpdatedDate = DateTime.Now
                                   };
                if (parentId.HasValue) exceptionLog.ParentId = parentId;

                uowRazaki.ExceptionLogRepository.Add(exceptionLog);
                if (uowRazaki.Save() == 1)
                    newRecordId = exceptionLog.Id;

                //recursive
                if (exc.InnerException != null && newRecordId > 0)
                {
                    Log(exc.InnerException, newRecordId);
                }

                result = 1;

                return result;
            }
        }
    }
}